#!/bin/bash

cd /sys/kernel/config/usb_gadget/
mkdir -p hb

cd hb
echo 0x0525 > idVendor # Linux Foundation
echo 0xa4a7 > idProduct # Multifunction Composite Gadget
echo 0x0001 > bcdDevice # v1.0.0
echo 0x0200 > bcdUSB # USB2
echo 0xEF > bDeviceClass
echo 0x02 > bDeviceSubClass
echo 0x01 > bDeviceProtocol

mkdir -p strings/0x409
echo "abcdefg1234567890" > strings/0x409/serialnumber
echo "raspberry" > strings/0x409/manufacturer
echo "hb" > strings/0x409/product

cfg=configs/c.1
mkdir -p "${cfg}"
echo 0x80 > ${cfg}/bmAttributes
echo 250 > ${cfg}/MaxPower

cfg_str=""
udc_dev=fe980000.usb

# The IP address shared by all USB network interfaces created by this script.
net_ip=192.168.55.1
# The associated netmask.
net_mask=255.255.255.0

# Note: RNDIS must be the first function in the configuration, or Windows'
# RNDIS support will not operate correctly.
enable_rndis=1
if [ ${enable_rndis} -eq 1 ]; then
cfg_str="${cfg_str}+RNDIS"
func=functions/rndis.usb0
mkdir -p "${func}"
ln -sf "${func}" "${cfg}"

# Informs Windows that this device is compatible with the built-in RNDIS
# driver. This allows automatic driver installation without any need for
# a .inf file or manual driver selection.
echo 1 > os_desc/use
echo 0xcd > os_desc/b_vendor_code
echo MSFT100 > os_desc/qw_sign
echo RNDIS > "${func}/os_desc/interface.rndis/compatible_id"
echo 5162001 > "${func}/os_desc/interface.rndis/sub_compatible_id"
ln -sf "${cfg}" os_desc
fi

enable_bulk=1
if [ ${enable_bulk} -eq 1 ]; then
mkdir -p /dev/usb-ffs

cfg_str="${cfg_str}+BULK1"
mkdir -p /dev/usb-ffs/bulk1
func=functions/ffs.bulk1
mkdir -p "${func}"
ln -sf "${func}" "${cfg}"
mount -o mode=0777 -o uid=2000 -o gid=2000 -t functionfs bulk1 /dev/usb-ffs/bulk1
/usr/local/bin/startup_bulk /dev/usb-ffs/bulk1 &
sleep 3

cfg_str="${cfg_str}+BULK2"
mkdir -p /dev/usb-ffs/bulk2
func=functions/ffs.bulk2
mkdir -p "${func}"
ln -sf "${func}" "${cfg}"
mount -o mode=0777 -o uid=2000 -o gid=2000 -t functionfs bulk2 /dev/usb-ffs/bulk2
/usr/local/bin/startup_bulk /dev/usb-ffs/bulk2 &
sleep 3

fi

mkdir -p "${cfg}/strings/0x409"
echo "${cfg_str:1}" > "${cfg}/strings/0x409/configuration"

udevadm settle -t 5 || :
#ls /sys/class/udc > UDC
ls /sys/class/udc/
echo "fc400000.usb" > UDC

/sbin/brctl addbr hbbr0
/sbin/ifconfig hbbr0 ${net_ip} netmask ${net_mask} up

if [ ${enable_rndis} -eq 1 ]; then
/sbin/brctl addif hbbr0 usb0
/sbin/ifconfig usb0 down
/sbin/ifconfig usb0 up
fi

exit 0

